<template>
  <div class="matched-orders-container">
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" @keyup.enter="handleQuery">
        <el-form-item label="供应商">
          <el-input v-model="queryParams.supplierName" clearable placeholder="供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNumber" clearable placeholder="订单编号"></el-input>
        </el-form-item>
        <el-form-item label="匹配结果">
          <el-select v-model="queryParams.matchResult" clearable placeholder="匹配结果" style="width: 120px;">
            <el-option label="匹配" value="匹配"></el-option>
            <el-option label="不匹配" value="不匹配"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
              v-model="dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格操作按钮 -->
    <div class="table-operations">
      <el-button :disabled="selectedItems.length === 0" type="danger" @click="handleBatchDelete">
        <el-icon>
          <Delete/>
        </el-icon>
        批量删除
      </el-button>
      <el-button type="success" @click="exportMatchData">
        <el-icon>
          <Download/>
        </el-icon>
        导出数据
      </el-button>
    </div>

    <el-table
        v-loading="loading"
        :data="matchedOrders"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="60"></el-table-column>
      <el-table-column label="订单信息" min-width="300">
        <template #default="scope">
          <div class="document-info">
            <div><strong>订单编号:</strong> {{ scope.row.orderNumber || '未知' }}</div>
            <div><strong>供应商:</strong> {{ scope.row.supplierName || '未知' }}</div>
            <div><strong>金额:</strong> {{ formatAmount(scope.row.orderAmount) }}</div>
            <div><strong>状态:</strong> {{ scope.row.orderStatus || '未知' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收货单信息" min-width="300">
        <template #default="scope">
          <div class="document-info">
            <div><strong>收货单编号:</strong> {{ scope.row.receiptNumber || '未知' }}</div>
            <div><strong>金额:</strong> {{ formatAmount(scope.row.receiptAmount) }}</div>
            <div><strong>状态:</strong> {{ scope.row.receiptStatus || '未知' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发票信息" min-width="300">
        <template #default="scope">
          <div class="document-info">
            <div><strong>发票编号:</strong> {{ scope.row.invoiceNumber || '未知' }}</div>
            <div><strong>金额:</strong> {{ formatAmount(scope.row.invoiceAmount) }}</div>
            <div><strong>开票日期:</strong> {{ scope.row.issueDate || '未知' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="匹配信息" min-width="200">
        <template #default="scope">
          <div class="document-info">
            <div><strong>匹配结果:</strong>
              <el-tag :type="scope.row.matchResult === '匹配' ? 'success' : 'danger'">
                {{ scope.row.matchResult || '未知' }}
              </el-tag>
            </div>
            <div><strong>匹配时间:</strong> {{ formatDateTime(scope.row.matchTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="viewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {batchDeleteMatch, exportMatch, getMatchedOrders} from '@/api/match';
import type {MatchedOrderVO} from '@/api/types';
import {useRouter} from 'vue-router';
import {Delete, Download} from '@element-plus/icons-vue';

const router = useRouter();

// 选中的项目
const selectedItems = ref<any[]>([]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

// 数据列表
const matchedOrders = ref<MatchedOrderVO[]>([]);
const total = ref(0);
const loading = ref(false);
const dateRange = ref<string[]>([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  supplierName: '',
  orderNumber: '',
  matchResult: '',
  startDate: '',
  endDate: ''
});

// 初始化
onMounted(() => {
  getMatchedOrdersList();
});

// 获取已匹配的订单列表
const getMatchedOrdersList = () => {
  loading.value = true;
  // 处理日期范围
  if (dateRange.value && dateRange.value.length > 0) {
    queryParams.startDate = dateRange.value[0];
    queryParams.endDate = dateRange.value[1];
  } else {
    queryParams.startDate = '';
    queryParams.endDate = '';
  }

  // 确保供应商名称参数被正确处理
  getMatchedOrders(queryParams)
      .then((res: any) => {
        if (res.code === 200) {
          matchedOrders.value = res.data.records;
          total.value = res.data.total;
        } else {
          ElMessage.error(res.message || '获取已匹配订单失败');
        }
      })
      .catch((error: any) => {
        console.error('获取已匹配订单失败', error);
        ElMessage.error('获取已匹配订单失败');
      })
      .finally(() => {
        loading.value = false;
      });
};

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getMatchedOrdersList();
};

// 重置
const resetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.supplierName = '';
  queryParams.orderNumber = '';
  queryParams.matchResult = '';
  dateRange.value = [];
  queryParams.startDate = '';
  queryParams.endDate = '';
  getMatchedOrdersList();
};

// 分页操作
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getMatchedOrdersList();
};

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getMatchedOrdersList();
};

// 查看详情
const viewDetail = (row: any) => {
  // 根据匹配ID或者订单ID跳转到详情页
  if (row.matchId) {
    router.push(`/dashboard/match/detail/${row.matchId}`);
  } else if (row.orderId) {
    // 如果没有匹配ID则通过订单ID查看
    router.push(`/dashboard/order-detail/${row.orderId}`);
  }
};

// 删除
// const handleDelete = (row: MatchedOrderVO) => {
//   ElMessageBox.confirm(`确认删除该匹配记录吗？`, '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     deleteMatch(row.matchId.toString()).then((res: any) => {
//       if (res.code === 200) {
//         ElMessage.success('删除成功');
//         getMatchedOrdersList();
//       } else {
//         ElMessage.error(res.message || '删除失败');
//       }
//     }).catch(() => {
//       ElMessage.error('删除失败');
//     });
//   }).catch(() => {
//   });
// };

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '未知';
  // 处理ISO格式的日期时间字符串
  if (dateTime.includes('T')) {
    return dateTime.replace('T', ' ').substring(0, 19);
  }
  // 如果是普通的日期时间字符串，直接返回
  return dateTime;
};

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '未知';
  return amount.toFixed(2);
};

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 条匹配记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = selectedItems.value.map(item => item.id);
    batchDeleteMatch(ids)
        .then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('批量删除成功');
            getMatchedOrdersList();
          } else {
            ElMessage.error(res.message || '批量删除失败');
          }
        })
        .catch((error: any) => {
          console.error('批量删除失败', error);
          ElMessage.error('批量删除失败');
        });
  }).catch(() => {
    // 取消操作
  });
};

// 导出数据
const exportMatchData = () => {
  // 根据当前筛选条件导出数据
  const params = {
    matchResult: queryParams.matchResult,
    orderNumber: queryParams.orderNumber,
    supplierName: queryParams.supplierName,
    startDate: dateRange.value && dateRange.value.length > 0 ? dateRange.value[0] : '',
    endDate: dateRange.value && dateRange.value.length > 0 ? dateRange.value[1] : '',
  };

  // 使用API调用导出
  exportMatch(params)
      .then((response: any) => {
        // 检查响应结构
        if (response.data && response.data.data instanceof Blob) {
          // 处理标准响应中包含Blob的情况
          const blob = response.data.data;
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          const currentDate = new Date().toISOString().split('T')[0];
          link.download = `匹配记录_${currentDate}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(link.href);
          ElMessage.success('导出成功');
        } else if (response instanceof Blob) {
          // 处理直接返回Blob的情况
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(response);
          const currentDate = new Date().toISOString().split('T')[0];
          link.download = `匹配记录_${currentDate}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(link.href);
          ElMessage.success('导出成功');
        } else if (response && typeof response === 'object' && response.data instanceof Blob) {
          // 处理响应对象中直接包含Blob的情况
          const blob = response.data;
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          const currentDate = new Date().toISOString().split('T')[0];
          link.download = `匹配记录_${currentDate}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(link.href);
          ElMessage.success('导出成功');
        } else {
          console.error('响应不是Blob类型:', response);
          ElMessage.error('导出失败: 响应格式不正确');
        }
      })
      .catch(error => {
        console.error('导出失败', error);
        ElMessage.error('导出失败');
      });
};

// 导出组件方法
defineExpose({
  getMatchedOrdersList
});
</script>

<style scoped>
.matched-orders-container {
  padding: 20px;
}

.search-form {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.table-operations {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
}

:deep(.el-button--success) {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
}

:deep(.el-button--danger:disabled) {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: white !important;
}

.document-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.document-info, .match-info {
  padding: 8px;
  font-size: 14px;
}

.document-info div, .match-info div {
  margin-bottom: 5px;
}

.difference {
  margin-top: 8px;
  color: #f56c6c;
}

/* 修复下拉框文本溢出问题 */
:deep(.el-select__tags-text) {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-select .el-tag) {
  max-width: 100%;
}

:deep(.el-select .el-tag--info) {
  display: flex;
}

:deep(.el-select .el-select__tags-text) {
  display: inline-block;
  max-width: calc(100% - 20px);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 